package com.wephone.Student.ui;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.Time;
import android.view.View;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.wephone.Student.R;
import com.wephone.Student.bean.BaseResponse;
import com.wephone.Student.bean.data.CityData;
import com.wephone.Student.bean.data.CountryData;
import com.wephone.Student.bean.data.ProvinceData;
import com.wephone.Student.bean.savedData.PurchasingSaveData;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.wheel.widget.OnWheelChangedListener;
import com.wephone.Student.wheel.widget.StringWheelAdapter;
import com.wephone.Student.wheel.widget.WheelView;

public class CreatePurchasingActivity extends BaseActivity {
	private int _year;
	private int _month;
	private int _day;
	private TextView inputEdit1;
	private TextView inputEdit2;
	private TextView inputEdit3;
	private EditText inputEdit4;
	private EditText inputEdit5;
	private static PurchasingSaveData purchasingSaveData = new PurchasingSaveData();
	private boolean notSave = false;
	private ProgressDialog progressDialog;
	private int nCountryIdx;
	private int nProvinceIdx;
	private int nCityIdx;
	private int nCountryIdx2;
	private int nProvinceIdx2;
	private int nCityIdx2;
	
	private MyResponseHandler getHandler(){
		MyResponseHandler handler = new MyResponseHandler(CreatePurchasingActivity.this,BaseResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(progressDialog!=null){
					progressDialog.dismiss();
				}
				if(getDataSuccess){
//					FlyTogetherListResponse res = (FlyTogetherListResponse)response;
					notSave = true;
					setResult(222);
					finish();
				}
			}
			
			@Override
			public void onFailure(Throwable arg0, String result) {
				super.onFailure(arg0, result);
				
				if(progressDialog!=null){
					progressDialog.dismiss();
				}
				Toast.makeText(getApplicationContext(), getString(R.string.network_error_txt), Toast.LENGTH_SHORT).show();
			}
		};
		return handler;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		inputEdit1.setText(purchasingSaveData.getInputStr1());
		inputEdit2.setText(purchasingSaveData.getInputStr2());
		inputEdit4.setText(purchasingSaveData.getInputStr3());
		inputEdit5.setText(purchasingSaveData.getInputStr4());
		if(!TextUtils.isEmpty(purchasingSaveData.getFlyTimeText())){
			inputEdit3.setText(purchasingSaveData.getFlyTimeText());
			_year = purchasingSaveData.getYear();
			_month = purchasingSaveData.getMonth();
			_day = purchasingSaveData.getDay();
		}
		nCountryIdx = purchasingSaveData.getnCountryIdx();
		nProvinceIdx = purchasingSaveData.getnProvinceIdx();
		nCityIdx = purchasingSaveData.getnCityIdx();
		nCountryIdx2 = purchasingSaveData.getnCountryIdx2();
		nProvinceIdx2 = purchasingSaveData.getnProvinceIdx2();
		nCityIdx2 = purchasingSaveData.getnCityIdx2();
	}

	@Override
	protected void onPause() {
		super.onPause();
		
		if(!notSave){
			purchasingSaveData.setInputStr1(inputEdit1.getText().toString());
			purchasingSaveData.setInputStr2(inputEdit2.getText().toString());
			purchasingSaveData.setInputStr3(inputEdit4.getText().toString());
			purchasingSaveData.setInputStr4(inputEdit5.getText().toString());
			if(!TextUtils.isEmpty(inputEdit3.getText().toString())){
				purchasingSaveData.setFlyTimeText(inputEdit3.getText().toString());
				purchasingSaveData.setYear(_year);
				purchasingSaveData.setMonth(_month);
				purchasingSaveData.setDay(_day);
			}
			purchasingSaveData.setnCountryIdx(nCountryIdx);
			purchasingSaveData.setnProvinceIdx(nProvinceIdx);
			purchasingSaveData.setnCityIdx(nCityIdx);
			purchasingSaveData.setnCountryIdx2(nCountryIdx2);
			purchasingSaveData.setnProvinceIdx2(nProvinceIdx2);
			purchasingSaveData.setnCityIdx2(nCityIdx2);
		}else{
			purchasingSaveData = new PurchasingSaveData();
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_purchasing);
		
		init();
	}
	
	private void init(){
		inputEdit1 = (TextView)findViewById(R.id.create_fly_input_edit_1);
		inputEdit2 = (TextView)findViewById(R.id.create_fly_input_edit_2);
		inputEdit3 = (TextView)findViewById(R.id.fly_time_text);
		inputEdit4 = (EditText)findViewById(R.id.create_fly_input_edit_4);
		inputEdit5 = (EditText)findViewById(R.id.create_fly_input_edit_5);
		
		inputEdit1.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showChooseCountryDialog1(getString(R.string.create_purchasing_item_1));
			}
		});
		inputEdit2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showChooseCountryDialog2(getString(R.string.create_purchasing_item_2));
			}
		});
		
		Time time = new Time("GMT+8");
		time.setToNow();
		_year = time.year;
		_month = time.month;
		_day = time.monthDay;
		
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		findViewById(R.id.fly_time_layout).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showChooseDateDialog();
			}
		});
		
		findViewById(R.id.btn_finish).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(checkInput()){
					progressDialog = ProgressDialog.show(CreatePurchasingActivity.this, "提示", "正在提交数据...", true, false);
					
					RequestParams params = new RequestParams();
					params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
					params.put("pFrom", inputEdit1.getText().toString());
					params.put("pTo", inputEdit2.getText().toString());
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					try {
						Date date = sdf.parse(_year+"-"+(_month+1)+"-"+_day);
						params.put("pTs", ""+date.getTime()/1000);
					} catch (ParseException e) {
						e.printStackTrace();
					}
					params.put("pTitle", inputEdit4.getText().toString());
					params.put("pDetail", inputEdit5.getText().toString());
					HttpClient.getInstance().post(Constants.API_ADD_PURCHASE_URL, params, getHandler());
				}
			}
		});
	}
	
	private boolean checkInput(){
		if(TextUtils.isEmpty(inputEdit1.getText().toString())){
			Toast.makeText(getApplicationContext(), "出发地必须填写", Toast.LENGTH_SHORT).show();
			return false;
		}else if(TextUtils.isEmpty(inputEdit2.getText().toString())){
			Toast.makeText(getApplicationContext(), "目的地必须填写", Toast.LENGTH_SHORT).show();
			return false;
		}else if(TextUtils.isEmpty(inputEdit3.getText().toString())){
			Toast.makeText(getApplicationContext(), "出行时间必须选择", Toast.LENGTH_SHORT).show();
			return false;
		}else if(TextUtils.isEmpty(inputEdit4.getText().toString().trim().replace("\n", ""))){
			Toast.makeText(getApplicationContext(), "标题必须填写", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	private void showChooseDateDialog(){
		new DatePickerDialog(this, new OnDateSetListener() {
            public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) {
                _year = year;
                _month = monthOfYear;
                _day = dayOfMonth;
                ((TextView)findViewById(R.id.fly_time_text)).setText(_year+"-"+(_month+1)+"-"+_day);
            }

        }, _year, _month, _day).show();
	}
	
	private void showChooseCountryDialog1(String title){
		View inputView = getLayoutInflater().inflate(R.layout.dialog_wheel_3_view, null);
		final WheelView wheel1 = (WheelView)inputView.findViewById(R.id.wheel_1);
		final WheelView wheel2 = (WheelView)inputView.findViewById(R.id.wheel_2);
		final WheelView wheel3 = (WheelView)inputView.findViewById(R.id.wheel_3);
		
		List<String> countryList = new ArrayList<String>();
		for(CountryData cd:BaseActivity.getCountryList(getApplicationContext())){
			countryList.add(cd.getN());
		}
        wheel1.setAdapter(new StringWheelAdapter(countryList));
        wheel1.setCurrentItem(nCountryIdx);
        wheel1.setCyclic(true);
        wheel1.setInterpolator(new AnticipateOvershootInterpolator());
        wheel1.addChangingListener(new OnWheelChangedListener(){
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				nCountryIdx = newValue;
				nProvinceIdx = 0;
				nCityIdx = 0;
				
				List<String> provinceList = new ArrayList<String>();
				for(ProvinceData cd:BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx).getP()){
					provinceList.add(cd.getN());
				}
		        wheel2.setAdapter(new StringWheelAdapter(provinceList));
		        wheel2.setCurrentItem(nProvinceIdx);
				
				List<String> cityList = new ArrayList<String>();
				for(CityData cd:BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx).getP().get(nProvinceIdx).getC()){
					cityList.add(cd.getN());
				}
				wheel3.setAdapter(new StringWheelAdapter(cityList));
				wheel3.setCurrentItem(nCityIdx);
			}});
		
		List<String> provinceList = new ArrayList<String>();
		for(ProvinceData cd:BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx).getP()){
			provinceList.add(cd.getN());
		}
        wheel2.setAdapter(new StringWheelAdapter(provinceList));
        wheel2.setCurrentItem(nProvinceIdx);
        wheel2.setCyclic(true);
        wheel2.setInterpolator(new AnticipateOvershootInterpolator());
        wheel2.addChangingListener(new OnWheelChangedListener(){
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				nProvinceIdx = newValue;
				nCityIdx = 0;
				
				List<String> cityList = new ArrayList<String>();
				for(CityData cd:BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx).getP().get(nProvinceIdx).getC()){
					cityList.add(cd.getN());
				}
				wheel3.setAdapter(new StringWheelAdapter(cityList));
				wheel3.setCurrentItem(nCityIdx);
			}});
        
		List<String> cityList = new ArrayList<String>();
		for(CityData cd:BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx).getP().get(nProvinceIdx).getC()){
			cityList.add(cd.getN());
		}
        wheel3.setAdapter(new StringWheelAdapter(cityList));
        wheel3.setCurrentItem(nCityIdx);
        wheel3.setCyclic(true);
        wheel3.setInterpolator(new AnticipateOvershootInterpolator());
        
		AlertDialog.Builder builder = new AlertDialog.Builder(CreatePurchasingActivity.this);
		builder.setTitle(title);
		builder.setView(inputView);  
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int whichButton){
				nCountryIdx = wheel1.getCurrentItem();
				nProvinceIdx = wheel2.getCurrentItem();
				nCityIdx = wheel3.getCurrentItem();
				if(TextUtils.isEmpty(BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx).getP().get(nProvinceIdx).getN())){
					inputEdit1.setText(BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx).getN()+" "+BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx).getP().get(nProvinceIdx).getC().get(nCityIdx).getN());
				}else{
					inputEdit1.setText(BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx).getN()+" "+BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx).getP().get(nProvinceIdx).getN()+" "+BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx).getP().get(nProvinceIdx).getC().get(nCityIdx).getN());
				}
			}
		});  
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int whichButton){}
		}); 
		builder.show();  
	}
	
	private void showChooseCountryDialog2(String title){
		View inputView = getLayoutInflater().inflate(R.layout.dialog_wheel_3_view, null);
		final WheelView wheel1 = (WheelView)inputView.findViewById(R.id.wheel_1);
		final WheelView wheel2 = (WheelView)inputView.findViewById(R.id.wheel_2);
		final WheelView wheel3 = (WheelView)inputView.findViewById(R.id.wheel_3);
		
		List<String> countryList = new ArrayList<String>();
		for(CountryData cd:BaseActivity.getCountryList(getApplicationContext())){
			countryList.add(cd.getN());
		}
        wheel1.setAdapter(new StringWheelAdapter(countryList));
        wheel1.setCurrentItem(nCountryIdx2);
        wheel1.setCyclic(true);
        wheel1.setInterpolator(new AnticipateOvershootInterpolator());
        wheel1.addChangingListener(new OnWheelChangedListener(){
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				nCountryIdx2 = newValue;
				nProvinceIdx2 = 0;
				nCityIdx2 = 0;
				
				List<String> provinceList = new ArrayList<String>();
				for(ProvinceData cd:BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx2).getP()){
					provinceList.add(cd.getN());
				}
		        wheel2.setAdapter(new StringWheelAdapter(provinceList));
		        wheel2.setCurrentItem(nProvinceIdx2);
				
				List<String> cityList = new ArrayList<String>();
				for(CityData cd:BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx2).getP().get(nProvinceIdx2).getC()){
					cityList.add(cd.getN());
				}
				wheel3.setAdapter(new StringWheelAdapter(cityList));
				wheel3.setCurrentItem(nCityIdx2);
			}});
		
		List<String> provinceList = new ArrayList<String>();
		for(ProvinceData cd:BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx2).getP()){
			provinceList.add(cd.getN());
		}
        wheel2.setAdapter(new StringWheelAdapter(provinceList));
        wheel2.setCurrentItem(nProvinceIdx2);
        wheel2.setCyclic(true);
        wheel2.setInterpolator(new AnticipateOvershootInterpolator());
        wheel2.addChangingListener(new OnWheelChangedListener(){
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				nProvinceIdx2 = newValue;
				nCityIdx2 = 0;
				
				List<String> cityList = new ArrayList<String>();
				for(CityData cd:BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx2).getP().get(nProvinceIdx2).getC()){
					cityList.add(cd.getN());
				}
				wheel3.setAdapter(new StringWheelAdapter(cityList));
				wheel3.setCurrentItem(nCityIdx2);
			}});
        
		List<String> cityList = new ArrayList<String>();
		for(CityData cd:BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx2).getP().get(nProvinceIdx2).getC()){
			cityList.add(cd.getN());
		}
        wheel3.setAdapter(new StringWheelAdapter(cityList));
        wheel3.setCurrentItem(nCityIdx2);
        wheel3.setCyclic(true);
        wheel3.setInterpolator(new AnticipateOvershootInterpolator());
        
		AlertDialog.Builder builder = new AlertDialog.Builder(CreatePurchasingActivity.this);
		builder.setTitle(title);
		builder.setView(inputView);  
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int whichButton){
				nCountryIdx2 = wheel1.getCurrentItem();
				nProvinceIdx2 = wheel2.getCurrentItem();
				nCityIdx2 = wheel3.getCurrentItem();
				if(TextUtils.isEmpty(BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx2).getP().get(nProvinceIdx2).getN())){
					inputEdit2.setText(BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx2).getN()+" "+BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx2).getP().get(nProvinceIdx2).getC().get(nCityIdx2).getN());
				}else{
					inputEdit2.setText(BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx2).getN()+" "+BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx2).getP().get(nProvinceIdx2).getN()+" "+BaseActivity.getCountryList(getApplicationContext()).get(nCountryIdx2).getP().get(nProvinceIdx2).getC().get(nCityIdx2).getN());
				}
			}
		});  
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int whichButton){}
		}); 
		builder.show();  
	}
	
}
